<?php

namespace app\dao;

use app\model\Resource;
use think\facade\Log;

class ResourceDao
{
    // 添加资源
    public static function addResource($projectId, $type, $title, $filePath, $externalUrl, $uploaderId)
    {
        try {
            return Resource::create([
                'project_id' => $projectId,
                'type' => $type,
                'title' => $title,
                'file_path' => $filePath,
                'external_url' => $externalUrl,
                'uploader_id' => $uploaderId
            ]);
        } catch (\Exception $e) {
            Log::error("添加资源失败: " . $e->getMessage());
            return null;
        }
    }

    // 根据项目 ID 获取所有资源
    public static function getResourcesByProjectId($projectId)
    {
        try {
            return Resource::where('project_id', $projectId)->select();
        } catch (\Exception $e) {
            Log::error("根据项目ID获取资源失败: " . $e->getMessage());
            return [];
        }
    }

    // 根据资源 ID 获取资源
    public static function getResourceById($id)
    {
        try {
            return Resource::find($id);
        } catch (\Exception $e) {
            Log::error("根据资源ID获取资源失败: " . $e->getMessage());
            return null;
        }
    }

    // 删除资源
    public static function deleteResource($id)
    {
        try {
            return Resource::where('id', $id)->delete();
        } catch (\Exception $e) {
            Log::error("删除资源失败: " . $e->getMessage());
            return false;
        }
    }

    // 更新资源信息
    public static function updateResource($id, array $data)
    {
        try {
            return Resource::where('id', $id)->update($data);
        } catch (\Exception $e) {
            Log::error("更新资源失败: " . $e->getMessage());
            return false;
        }
    }
}
